INSERT INTO history
SELECT history_id_seq.NEXTVAL, pur_date,pur_quantity,switch_id, event_id FROM
(SELECT MAX(d) - 7 pur_date, 4 switch_id, SUM(total_ports) * 2 / devices.ports_num pur_quantity, 1 event_id FROM
(SELECT history_date d, quantity * ports_num total_ports FROM history, devices
WHERE history.event = 5 AND history.device = devices.device_id) tmp, devices
WHERE device_id = 4
GROUP BY devices.ports_num);
INSERT INTO history
SELECT history_id_seq.NEXTVAL, pur_date,pur_quantity,switch_id, event_id FROM
(SELECT MAX(d) - 7 pur_date, 4 switch_id, SUM(total_ports) * 2 / devices.ports_num pur_quantity, 1 event_id FROM
(SELECT history_date d, quantity * ports_num total_ports FROM history, devices
WHERE history.event = 7 AND history.device = devices.device_id) tmp, devices
WHERE device_id = 4
GROUP BY devices.ports_num);

INSERT INTO history
SELECT history_id_seq.NEXTVAL, history_date + 6,quantity,device, 2 FROM history
WHERE history_id=20;
INSERT INTO history
SELECT history_id_seq.NEXTVAL, history_date + 6,quantity,device, 3 FROM history
WHERE history_id=21;